import React, { useEffect, useState } from 'react'
import { Button, Modal, Form, Input } from 'antd';
import axios from '../../aixos';
import Table from '../../components/Table/Table'
import Image from '../../components/Image/Image'
import Upload from '../../components/Upload/Upload'

export default function Banner() {
  const [bannerList, setBannerList] = useState([])
  const [total, setTotal] = useState(0)
  const [pageIndex, setPageIndex] = useState(1)
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState(null)
  const [editRecordId, setEditRecordId] = useState(null)
  const [imageUrl, setImageUrl] = useState('')
  
  const pageSize = 10
  useEffect(() => {
    axios.get('/banner', {
      pageIndex,
      pageSize
    }).then(res => {
      setBannerList(res.data.records)
      setTotal(res.data.total)
    })
  }, [pageIndex])
  const changePage = (index) => {
    setPageIndex(index)
  }
  const add = () => {
    form.resetFields()
    setImageUrl('')
    setModalTitle('添加')
    setIsModalVisible(true)
  }
  
  const handleCancel = () => {
    setIsModalVisible(false);
  };
  
  const edit = (record) => {
    setImageUrl(record.imageUrl)
    setModalTitle('编辑')
    setEditRecordId(record._id)
    form.setFieldsValue({...record})
    setIsModalVisible(true)
  }
  const del = (id) => {
    axios.delete('/banner', {
      id
    }).then(() => {
      setBannerList(bannerList.filter(item => item._id !==id))
    })
  }

  const submit = async () => {
    console.log(form.getFieldsValue())
    console.log(form.getFieldValue('imageUrl'))
    const formData = await form.validateFields()
    if (!editRecordId) {
      axios.post('/banner', formData).then(res => {
        setBannerList([res.data, ...bannerList])
        setIsModalVisible(false);
      })
    } else {
      axios.put('/banner', {
        id: editRecordId,
        ...formData
      }).then(() => {
        setBannerList(bannerList.map(item => {
          if (item._id === editRecordId) return { ...item, ...formData } 
          return item
        }))
        setIsModalVisible(false)
      })
    }
  };

  const [form] = Form.useForm();
  const columns = [
    {
      title: '图片',
      dataIndex: 'imageUrl',
      render: url => <Image src={url} />,
    },
    {
      title: '标语',
      dataIndex: 'slogan'
    },
    {
      title: '跳转链接',
      dataIndex: 'url',
      render: url => <a href={url}>{url}</a>
    }
    // {
    //   title: '操作',
    //   render: (_, record) => (
    //     <Space size="middle">
    //       <Button type='primary' onClick={() => edit(record)}>编辑</Button>
    //       <Button type='danger' onClick={() => del(record._id)}>删除</Button>
    //     </Space>
    //   ),
    // },
  ];
  return (
    <div>
      <Table rowKey='_id' columns={columns} dataSource={bannerList}  pagination={{
        current: pageIndex,
        pageSize: pageSize,
        total: total,
        showTotal: () => `共 ${total} 条数据`,
        onChange: changePage
      }} 
      action={{
        edit: {callback: edit},
        delete: {callback: del}
      }}
      >
        <Button onClick={add}>添加轮播</Button>
      </Table>
      <Modal title={modalTitle} cancelText='取消' okText='确认'
        visible={isModalVisible} onOk={submit} onCancel={handleCancel}>
        <Form
          form={form}
          name="basic"
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 16,
          }}
          initialValues={{
            remember: true,
          }}
          autoComplete="off"
        >
          <Form.Item label="轮播图片" name="imageUrl" required  rules={
            [
              {
                required: true,
                message: '请选择分类'
              }
            ]
          }>
            <Upload imageUrl={imageUrl} setImageUrl={(url) => {
              form.setFieldsValue({imageUrl: url})
              setImageUrl(url)
            }} />
          </Form.Item>
          <Form.Item
            label="标语"
            name="slogan"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="跳转链接"
            name="url"
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
